<?php
class IssueController extends Zend_Controller_Action
{
	protected $_acl;
	protected $_userGroup;
	
	public function init()
	{
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		$groupBase = new GroupBase();
		if ($userInfo) {
			$userGroups = $groupBase->getUserGroup($userInfo->name);
		}
		$this->_userGroup = $userGroups[0]['name'] ? $userGroups[0]['name'] : "Users";
		$this->_acl = new Acl_PPMIS();
		$this->view->acl = $this->_acl;
		$this->view->userGroup = $this->_userGroup;
	}
	
	public function preDispatch()
	{
		$auth = Zend_Auth::getInstance();
		if($auth->getIdentity()) {
			$this->view->auth = "success";
			$userInfo = $auth->getStorage()->read();
			$this->view->userInfo = $userInfo;
		}
		$Configuration = new Configuration();
		$configurationData = $Configuration->getConfigurationInfo();
		$this->view->configuration = $configurationData;
		//$this->view->auth = 'Success';
	}
	
	public function browseAction()
	{
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		$projectId = $this->_getParam('projectId');
		$issue = new Issue();
		$where = "project = $projectId";
		if($this->_getParam('fixfor')== -1) {
			$where .=' And (issue.id NOT IN (SELECT source_node_id from nodeassociation
												where association_type = "IssueFixVersion"))';
		}
		
		if($this->_getParam('assigneeSelect') == 'issue_current_user') {
			$where .= " And issue.assignee = '".$userInfo->fullname."'";
		}
		
		if($this->_getParam('reporterSelect') == 'issue_current_user') {
			$where .= " And issue.reporter = '".$userInfo->fullname."'";
		}
		
		if($this->_getParam('created') == '-1w') {
			$date = new Zend_Date();
			$date->sub(1, Zend_Date::WEEK);
			$today = $date->get();
			$where .= " And issue.created >= '".date('Y-m-d',$today)."'";
		}
		
		if($this->_getParam('updated') == '-1w') {
			$date = new Zend_Date();
			$date->sub(1, Zend_Date::WEEK);
			$today = $date->get();
			$where .= " And issue.updated >= '".date('Y-m-d',$today)."'";
		}
		
		if($this->_getParam('resolved') == '-1w') {
			$where .= " AND (issue.issuestatus IN (SELECT id FROM issuestatus WHERE pname = 'Closed' OR pname = 'Resolved'))";
			$date = new Zend_Date();
			$date->sub(1, Zend_Date::WEEK);
			$today = $date->get();
			$where .= " And issue.updated >= '".date('Y-m-d',$today)."'";
		}
		
		$project = new Project();
		$projectData = $project->getAdapter()->fetchRow($project->select()->where('id=?',$projectId));
		
		$issuesData = $issue->getIssues($where);
		$this->view->issuesData = $issuesData;
		$this->view->projectData = $projectData;
	}
	
	public function manageAction()
	{
		$this->view->current = "project";
		$Issue = new Issue();
		
		$cid = $this->_getParam('cid');
		
		$issues = $Issue->getIssuesByComponentId($cid);
		//Zend_Debug::dump($issues);
		
		$this->view->issues = $issues;
	}
	
	public function allAction()
	{
		$id = $this->_getParam('id');
		$action = new Action();
		$issue = new Issue();
		$fileAttachment = new FileAttachment();
		$changeItem = new ChangeItem();
		
		$issueLink = new IssueLink();
		$duplicatedIssues = $issueLink->getDuplicatedIssues($id);
		$duplicateIssues = $issueLink->getDuplicateIssues($id);
		
		$db = Zend_Registry::get('db');
		$iData = $issue->getIssueRow($id);
		$results = $db->fetchAll("(
						SELECT id, author, created, action_body
						FROM action WHERE action_type = 'comment'
						AND action.issueid =$id
						)
						UNION ALL (
						
						SELECT id, author, created, NULL AS action_body
						FROM changegroup
						WHERE changegroup.issueid = $id
						)
						ORDER BY created");
						
		//Zend_Debug::dump($results);exit;
		$data = array();
		$i = 0;
		foreach ($results  as $result) {
			if($result['action_body']) {
				$data[$i]['type'] = 'comment';
				$data[$i]['author'] = $result['author'];
				$data[$i]['created'] = $result['created'];
				$data[$i]['action_body'] = $result['action_body'];
			} else {
				$data[$i]['type'] = 'history';
				$data[$i]['author'] = $result['author'];
				$data[$i]['created'] = $result['created'];
				$data[$i]['items'] = $changeItem->getChangeItemsData($result['id']);
			}
			$i++;
		}
		$Project = new Project();
		$projectData = $Project->getAdapter()->fetchRow($Project->select()
									->from('project',array('id','pname'))
									->where('id = ?',$iData['project']));
									
		$component = new Component();
		$componentsData = $component->getIssueComponents($id);
		$attachments = $fileAttachment->getIssueAttachments($id);
		
		$projectVersion = new ProjectVersion();
		$issueFixVersions = $projectVersion->getIssueFixVersions($id);
		$issueAffectVersions = $projectVersion->getIssueAffectVersions($id);
		
		$this->view->duplicateIssues = $duplicateIssues;
		$this->view->duplicatedIssues = $duplicatedIssues;
		$this->view->attachments = $attachments;
		$this->view->projectData = $projectData;
		$this->view->components = $componentsData;
		$this->view->data = $iData;
		$this->view->issueFixVersions = $issueFixVersions;
		$this->view->issueAffectVersions = $issueAffectVersions;
		$this->view->issueData = $data;
		$this->view->id = $id;
		//Zend_Debug::dump($data);exit;
	}
	
	public function viewAction()
	{
		$zend_Auth = new Zend_Session_Namespace('Zend_Auth');
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		
		// code for Acl
		$groupBase = new GroupBase();
		
		$form = new CreateIssueStep1Form();
		
		$this->view->current = "project";
		$Issue = new Issue();
		$fileAttachment = new FileAttachment();
		
		$id = $this->_getParam('id',1);
		
		$Action = new Action();
		$issueLink = new IssueLink();
		$duplicatedIssues = $issueLink->getDuplicatedIssues($id);
		$duplicateIssues = $issueLink->getDuplicateIssues($id);
		// for seach
		if ($zend_Auth->filterXml) {
			$params = $this->_processXml($zend_Auth->filterXml);
			$sWhere = $this->_buildWhere($params);
			$sIssuesResults = $Issue->getIssues($sWhere);
			$searchResults = array();
			$searchResults['total'] = count($sIssuesResults);
			foreach ($sIssuesResults as $result) {
				if ($result['id'] == $id) {
					$searchResults['current']['issue'] = $i+1;
					$searchResults['current']['id'] = $result['id'];
					$searchResults['current']['pkey'] = $result['pkey'];
					if ($sIssuesResults[$i-1]['id']) {
						$searchResults['previous']['id'] = $sIssuesResults[$i-1]['id'];
						$searchResults['previous']['pkey'] = $sIssuesResults[$i-1]['pkey'];
					}
				
					if ($sIssuesResults[$i+1]['id']) {
						$searchResults['next']['id'] = $sIssuesResults[$i+1]['id'];
						$searchResults['next']['pkey'] = $sIssuesResults[$i+1]['pkey'];
					}
				}	
			$i++;
			}
		}
		
		$iData = $Issue->getIssueRow($id);
		
		// creating an instance of comment form
		$form = new AddCommentsForm();
		if ($this->getRequest()->isPost()) {
			$formData = $this->_request->getPost();
			if ($form->isValid($formData)) {
				//Zend_Debug::dump($formData);
				if (isset($formData['add'])) {
					unset($formData['add']);
					//Zend_Debug::dump($formData);
					$formData['action_type'] = 'comment';
					$formData['created'] = new Zend_Db_Expr('NOW()');
					$formData['updated'] = new Zend_Db_Expr('NOW()');
					$formData['author'] = $userInfo->fullname;
					//Zend_Debug::dump($formData);
					$Action->insert($formData);
				}
			}
		}
		$Component = new Component();
		// id is issue.id
		$componentsData = $Component->getIssueComponents($id);
		$attachments = $fileAttachment->getIssueAttachments($id);
		//Zend_Debug::dump($attachments);
		$Project = new Project();
		$projectData = $Project->getAdapter()->fetchRow($Project->select()
									->from('project',array('id','pname'))
									->where('id = ?',$iData['project']));
		
		$projectVersion = new ProjectVersion();
		$issueFixVersions = $projectVersion->getIssueFixVersions($id);
		$issueAffectVersions = $projectVersion->getIssueAffectVersions($id);
		$commentsData = $Action->fetchAll($Action->select()
						->where('issueid = ?',$iData['id'])
						->where('action_type = ?','comment'));
						
		//Zend_Debug::dump($iData);
		$this->view->searchResults = $searchResults;
		$this->view->duplicateIssues = $duplicateIssues;
		$this->view->duplicatedIssues = $duplicatedIssues;				
		$this->view->attachments = $attachments;
		$this->view->projectData = $projectData;
		$this->view->components = $componentsData;
		$this->view->data = $iData;
		$this->view->issueFixVersions = $issueFixVersions;
		$this->view->issueAffectVersions = $issueAffectVersions;
		$this->view->comments = $commentsData->toArray();
		$this->view->form = $form;
		$this->view->id = $id;
		
	}
	
	function changehistoryAction()
	{
		$Issue = new Issue();
		$fileAttachment = new FileAttachment();
		$changeItem = new ChangeItem();
		$changeGroup = new ChangeGroup();
		
		$issueId = $this->_getParam('issueId',1);
		
		$issueLink = new IssueLink();
		$duplicatedIssues = $issueLink->getDuplicatedIssues($issueId);
		$duplicateIssues = $issueLink->getDuplicateIssues($issueId);
		
		$Action = new Action();
		$iData = $Issue->getIssueRow($issueId);;
		//$iData = $issueData->toArray();
		
		$Component = new Component();
		// id is issue.id
		$componentsData = $Component->getIssueComponents($issueId);
		
		$Project = new Project();
		$projectData = $Project->getAdapter()->fetchRow($Project->select()
									->from('project',array('id','pname'))
									->where('id = ?',$iData['project']));
									
		$issueChangeGroups = $changeGroup->getIssueChangeGroups($issueId);
		//Zend_Debug::dump($issueChangeGroups);
		$historyData = array();
		foreach ($issueChangeGroups as $changeGroup) {
			$historyData[$changeGroup['id']]['author'] = $changeGroup['author']; 
			$historyData[$changeGroup['id']]['created'] = $changeGroup['created']; 
			$historyData[$changeGroup['id']]['items'] = $changeItem->getChangeItemsData($changeGroup['id']);
		}
		$attachments = $fileAttachment->getIssueAttachments($issueId);
		//$historyData = $changeItem->getChangeHistory($issueId);
		//Zend_Debug::dump($historyData);exit;
		
		$this->view->duplicateIssues = $duplicateIssues;
		$this->view->duplicatedIssues = $duplicatedIssues;
		$this->view->attachments = $attachments;
		$this->view->projectData = $projectData;
		$this->view->components = $componentsData;
		$this->view->changeHistory = $historyData;
		$this->view->data = $iData;
		$this->view->issueId = $issueId;
	}
	
	public function searchAction()
	{
		
		$projectId = $this->_getParam('pid',1);
		$issueType = new IssueType();
		$component = new Component();
		$priority = new Priority();
		$issueStatus = new IssueStatus();
		$resolution = new Resolution();
		$issueTypeData = $issueType->getAdapter()->fetchAll($issueType->select());
		
		$components = $component->getAdapter()->fetchAll($component->select()->where('project = ?', $projectId));
		
		$statusData = $issueStatus->getAdapter()->fetchAll($issueStatus->select());
		
		$priorities = $priority->getAdapter()->fetchAll($priority->select());
		
		$resolutions = $resolution->getAdapter()->fetchAll($resolution->select());
		
		$this->view->statusData = $statusData;
		$this->view->priorities = $priorities;
		$this->view->resolutions = $resolutions;
		$this->view->components = $components;
		$this->view->issueTypeData = $issueTypeData;
	}
	public function createstep1Action()
	{
		$user = Zend_Auth::getInstance()->getIdentity();
		$groupBase = new GroupBase();
		$userGroups = $groupBase->getUserGroup($user->name);
		$userGroup = $userGroups[0]['name'];
		$form = new CreateIssueStep1Form();
		$acl = new Acl_PPMIS();
		if ($acl->isAllowed($userGroup, null, "createissue"))
		{
			if ($this->getRequest()->isPost()) {
				$formData = $this->_request->getPost();
				if ($form->isValid($formData)) {
					$url = 'issue/createstep2/project/'.$formData['project'].'/issuetype/'.$formData['issuetype'];
					$this->_redirect($url);
				}
			}
			$IssueType = new IssueType();
			$issueTypeList = $IssueType->getList();
			$this->view->issueTypeList = $issueTypeList;
			$this->view->form = $form;
		} else {
			throw new Exception("Permission denied");
		}
	}
	
	public function createstep2Action()
	{
		$this->view->inc_yui = true;
		$this->view->inc_jquery = true;
		$this->view->current = 'createissue';
		$acl = new Acl_PPMIS();
		$issue = new Issue();
		$project = new Project();
		$nodeAssociation = new NodeAssociation();
		
		$form = new CreateIssueForm();
		
		if ($this->getRequest()->isPost()) {
			$formData = $this->_request->getPost();
			if ($form->isValid($formData)) {
				$pkey = $project->getAdapter()->fetchOne($project->select()
												->from('project','pkey')
												->where('id = ?',$formData['project']));
				$data = array(
					'project' => $formData['project'],
					'reporter' => $formData['reporter'],
					'assignee' => 'Faheem Abbas',
					'issueType' => $formData['issuetype'],
					'summary' => $formData['summary'],
					'description' => $formData['description'],
					'priority' => $formData['priority'],
					'resolution' => null,
					'issuestatus' => 1,
					'created' => new Zend_Db_Expr('NOW()'),
					'updated' => new Zend_Db_Expr('NOW()'),
					'duedate' => new Zend_Db_Expr('NOW()'),
					'timeestimate' => 25,
				);
				//Zend_Debug::dump($data);
				$issue->insert($data);
				$issueId = $issue->getAdapter()->lastInsertId();
				$pkey = $pkey.'-'.$issueId;
				$issue->update(array('pkey' => $pkey),"id = $issueId");
				foreach($formData['components'] as $componentId) {
					$compData = array(
							'source_node_id' => $issueId,
							'source_node_entity' => 'Issue',
							'sink_node_id' => $componentId,
							'sink_node_entity' => 'Component',
							'association_type' => 'IssueComponent'
					);
					/*$compData = array(
							'issue' => $issueId,
							'component' => $componentId
					);*/
					$nodeAssociation->insert($compData);
				}
				
				foreach($formData['affectVersions'] as $affectVersionId) {
					$versionData = array(
							'source_node_id' => $issueId,
							'source_node_entity' => 'Issue',
							'sink_node_id' => $affectVersionId,
							'sink_node_entity' => 'Version',
							'association_type' => 'IssueVersion'
					);
					/*$compData = array(
							'issue' => $issueId,
							'component' => $componentId
					);*/
					$nodeAssociation->insert($versionData);
				}
				
				foreach($formData['fixVersions'] as $fixVersionId) {
					$versionData = array(
							'source_node_id' => $issueId,
							'source_node_entity' => 'Issue',
							'sink_node_id' => $fixVersionId,
							'sink_node_entity' => 'Fix Version',
							'association_type' => 'IssueFixVersion'
					);
					/*$compData = array(
							'issue' => $issueId,
							'component' => $componentId
					);*/
					$nodeAssociation->insert($versionData);
				}
				
				$this->_redirect('issue/view/id/'.$issueId);
			}
		}
		// for <select> css
		$Priority = new Priority();
		$priorityList = $Priority->getList();
		$this->view->priorityList = $priorityList;
		$this->view->form = $form;
	}
	
	public function editAction()
	{
		$this->view->inc_yui = true;
		
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		
		$issueId = $this->_getParam('issueId');
		$issue = new Issue();
		$projectVersion = new ProjectVersion();
		$changeGroup = new ChangeGroup();
		$changeItem = new ChangeItem();
		$component = new Component();
		$nodeAssociation = new NodeAssociation();
		$form = new EditIssueForm();
		if ($this->getRequest()->isPost()) {
			$formData = $this->_request->getPost();
			if ($form->isValid($formData)) {
				$data = array(
					'reporter' => $formData['reporter'],
					'assignee' => 'Faheem Abbas',
					//'issueType' => $formData['issuetype'],
					'summary' => $formData['summary'],
					'description' => $formData['description'],
					'priority' => $formData['priority'],
					'resolution' => $formData['resolution'],
					'issuestatus' => $formData['issuestatus'],
					//'created' => new Zend_Db_Expr('NOW()'),
					'updated' => new Zend_Db_Expr('NOW()'),
					'duedate' => new Zend_Db_Expr('NOW()'),
					'timeestimate' => 25,
				);
				//Zend_Debug::dump($data);
				$issue->update($data, "id = ".$formData['id']);
				
				$where = "source_node_id = '". $formData['id']."' AND association_type = 'IssueComponent'";
				$oldComponents = $nodeAssociation->getAdapter()->fetchAll($nodeAssociation->select()
														->from('nodeassociation','sink_node_id')
														->where($where));
				$oldCompData = array();
				foreach ($oldComponents as $c) {
					$oldCompData[] = $c['sink_node_id'];
				}
				//Zend_Debug::dump($formData['components']);
				//Zend_Debug::dump($oldCompData);exit;
				$where = "source_node_id = '". $formData['id']."' AND association_type = 'IssueComponent'";
				$nodeAssociation->delete($where);
				foreach($formData['components'] as $componentId) {
					if (in_array($componentId, $oldCompData)) {
						$compData = array(
							'source_node_id' => $formData['id'],
							'source_node_entity' => 'Issue',
							'sink_node_id' => $componentId,
							'sink_node_entity' => 'Component',
							'association_type' => 'IssueComponent'
						);
					
						$nodeAssociation->insert($compData);
					} else {
						$componentRow = $component->getAdapter()->fetchRow($component->select()
														->from('component',array('id','cname'))
														->where('id = ?',$componentId));
						//Zend_Debug::dump($componentRow);exit;
						if (!$groupId) {
							$groupData = array(
								'issueid' => $formData['id'],
								'author' => $userInfo->fullname,
								'created' => new Zend_Db_Expr('NOW()')
							);
					
							$changeGroup->insert($groupData);
							$groupId = $changeGroup->getAdapter()->lastInsertId();
						}
						
						$changeItemData = array(
							'groupid' => $groupId,
							'fieldtype' => 'ppmis',
							'field' => 'component',
							'newvalue' => $componentRow['id'],
							'newstring' => $componentRow['cname']
						);
						$changeItem->insert($changeItemData);
						
						$compData = array(
							'source_node_id' => $formData['id'],
							'source_node_entity' => 'Issue',
							'sink_node_id' => $componentId,
							'sink_node_entity' => 'Component',
							'association_type' => 'IssueComponent'
						);
					
						$nodeAssociation->insert($compData);
					}
				} // end hanlding compnents
				
				foreach ($oldCompData as $oldComponent) {
					if (in_array($oldComponent, $formData['components'])) {
					} else {
						$componentName = $component->getAdapter()->fetchOne($component->select()
															->from('component','cname')
															->where('id = ?', $oldComponent));
						if (!$groupId) {
							$groupData = array(
								'issueid' => $formData['id'],
								'author' => $userInfo->fullname,
								'created' => new Zend_Db_Expr('NOW()')
							);
					
							$changeGroup->insert($groupData);
							$groupId = $changeGroup->getAdapter()->lastInsertId();
						}
						$changeItemData = array(
							'groupid' => $groupId,
							'fieldtype' => 'ppmis',
							'field' => 'component',
							'oldvalue' => $oldComponent,
							'oldstring' => $componentName
						);
						$changeItem->insert($changeItemData);
					}
				} // end of old component handling.....
				
				/*$where = "source_node_id = '". $formData['id']."' AND association_type = 'IssueComponent'";
				$nodeAssociation->delete($where);
				foreach($formData['components'] as $componentId) {
					$compData = array(
							'source_node_id' => $formData['id'],
							'source_node_entity' => 'Issue',
							'sink_node_id' => $componentId,
							'sink_node_entity' => 'Component',
							'association_type' => 'IssueComponent'
					);
					
					$nodeAssociation->insert($compData);
				}*/
				// code for updating affect versions
				
				$where = "source_node_id = '". $formData['id']."' AND association_type = 'IssueVersion'";
				$oldAffectVersions = $nodeAssociation->getAdapter()->fetchAll($nodeAssociation->select()
														->from('nodeassociation','sink_node_id')
														->where($where));
				$oldAffectVersionData = array();
				foreach ($oldAffectVersions as $v) {
					$oldAffectVersionData[] = $v['sink_node_id'];
				}
				
				$where = "source_node_id = '". $formData['id']."' AND association_type = 'IssueVersion'";
				$nodeAssociation->delete($where);
				foreach($formData['affectVersions'] as $affectVersionId) {
					if (in_array($affectVersionId, $oldAffectVersionData)) {
						$versionData = array(
							'source_node_id' => $formData['id'],
							'source_node_entity' => 'Issue',
							'sink_node_id' => $affectVersionId,
							'sink_node_entity' => 'Version',
							'association_type' => 'IssueVersion'
						);
					
						$nodeAssociation->insert($versionData);
					} else {
						$versionRow = $projectVersion->getAdapter()
													->fetchRow($projectVersion->select()
													->from('projectversion',array('id','vname'))
													->where('id = ?',$affectVersionId));
						if (!$groupId) {
							$groupData = array(
								'issueid' => $formData['id'],
								'author' => $userInfo->fullname,
								'created' => new Zend_Db_Expr('NOW()')
							);
					
							$changeGroup->insert($groupData);
							$groupId = $changeGroup->getAdapter()->lastInsertId();
						}
						
						$changeItemData = array(
							'groupid' => $groupId,
							'fieldtype' => 'ppmis',
							'field' => 'Affect Version',
							'newvalue' => $versionRow['id'],
							'newstring' => $versionRow['vname']
						);
						$changeItem->insert($changeItemData);
						
						$versionData = array(
							'source_node_id' => $formData['id'],
							'source_node_entity' => 'Issue',
							'sink_node_id' => $affectVersionId,
							'sink_node_entity' => 'Version',
							'association_type' => 'IssueVersion'
						);
					
						$nodeAssociation->insert($versionData);
					}
				} // end of affect version handling.
				
				foreach ($oldAffectVersionData as $oldAffectVersion) {
					if (in_array($oldAffectVersion, $formData['affectVersions'])) {
					} else {
						$affectVersionName = $projectVersion->getAdapter()->fetchOne($projectVersion->select()
														->from('projectversion','vname')
														->where('id = ?', $oldAffectVersion));
						if (!$groupId) {
							$groupData = array(
								'issueid' => $formData['id'],
								'author' => $userInfo->fullname,
								'created' => new Zend_Db_Expr('NOW()')
							);
					
							$changeGroup->insert($groupData);
							$groupId = $changeGroup->getAdapter()->lastInsertId();
						}
						$changeItemData = array(
							'groupid' => $groupId,
							'fieldtype' => 'ppmis',
							'field' => 'Affect Version',
							'oldvalue' => $oldAffectVersion,
							'oldstring' => $affectVersionName
						);
						$changeItem->insert($changeItemData);
					}
				} // end of old component handling.....
				
				/*$where = "source_node_id = '". $formData['id']."' AND association_type = 'IssueVersion'";
				$nodeAssociation->delete($where);
				foreach($formData['affectVersions'] as $affectVersionId) {
					$versionData = array(
							'source_node_id' => $formData['id'],
							'source_node_entity' => 'Issue',
							'sink_node_id' => $affectVersionId,
							'sink_node_entity' => 'Version',
							'association_type' => 'IssueVersion'
					);
					
					$nodeAssociation->insert($versionData);
				}*/
				// code for fix version
				$where = "source_node_id = '". $formData['id']."' AND association_type = 'IssueFixVersion'";
				$oldFixVersions = $nodeAssociation->getAdapter()->fetchAll($nodeAssociation->select()
														->from('nodeassociation','sink_node_id')
														->where($where));
				$oldFixVersionData = array();
				foreach ($oldFixVersions as $v) {
					$oldFixVersionData[] = $v['sink_node_id'];
				}
				$where = "source_node_id = '". $formData['id']."' AND association_type = 'IssueFixVersion'";
				$nodeAssociation->delete($where);
				foreach($formData['fixVersions'] as $fixVersionId) {
					if (in_array($fixVersionId, $oldFixVersionData)) {
						$versionData = array(
							'source_node_id' => $formData['id'],
							'source_node_entity' => 'Issue',
							'sink_node_id' => $fixVersionId,
							'sink_node_entity' => 'Fix Version',
							'association_type' => 'IssueFixVersion'
						);
					
						$nodeAssociation->insert($versionData);
					} else {
						$versionRow = $projectVersion->getAdapter()
													->fetchRow($projectVersion->select()
													->from('projectversion',array('id','vname'))
													->where('id = ?',$fixVersionId));
						if (!$groupId) {
							$groupData = array(
								'issueid' => $formData['id'],
								'author' => $userInfo->fullname,
								'created' => new Zend_Db_Expr('NOW()')
							);
					
							$changeGroup->insert($groupData);
							$groupId = $changeGroup->getAdapter()->lastInsertId();
						}
						
						$changeItemData = array(
							'groupid' => $groupId,
							'fieldtype' => 'ppmis',
							'field' => 'Fix Version',
							'newvalue' => $versionRow['id'],
							'newstring' => $versionRow['vname']
						);
						$changeItem->insert($changeItemData);
						
						$versionData = array(
							'source_node_id' => $formData['id'],
							'source_node_entity' => 'Issue',
							'sink_node_id' => $fixVersionId,
							'sink_node_entity' => 'Fix Version',
							'association_type' => 'IssueFixVersion'
						);
					
						$nodeAssociation->insert($versionData);
					}
				}
				
				foreach ($oldFixVersionData as $oldFixVersion) {
					if (in_array($oldFixVersion, $formData['fixVersions'])) {
					} else {
						$fixVersionName = $projectVersion->getAdapter()->fetchOne($projectVersion->select()
														->from('projectversion','vname')
														->where('id = ?', $oldFixVersion));
						if (!$groupId) {
							$groupData = array(
								'issueid' => $formData['id'],
								'author' => $userInfo->fullname,
								'created' => new Zend_Db_Expr('NOW()')
							);
					
							$changeGroup->insert($groupData);
							$groupId = $changeGroup->getAdapter()->lastInsertId();
						}
						$changeItemData = array(
							'groupid' => $groupId,
							'fieldtype' => 'ppmis',
							'field' => 'Fix Version',
							'oldvalue' => $oldFixVersion,
							'oldstring' => $fixVersionName
						);
						$changeItem->insert($changeItemData);
					}
				} // end of old component handling.....
				
				/*$where = "source_node_id = '". $formData['id']."' AND association_type = 'IssueFixVersion'";
				$nodeAssociation->delete($where);
				foreach($formData['fixVersions'] as $fixVersionId) {
					$versionData = array(
							'source_node_id' => $formData['id'],
							'source_node_entity' => 'Issue',
							'sink_node_id' => $fixVersionId,
							'sink_node_entity' => 'Fix Version',
							'association_type' => 'IssueFixVersion'
					);
					
					$nodeAssociation->insert($versionData);
				}*/
				$this->_redirect('issue/view/id/'.$formData['id']);
			}
		}
		$issueData = $issue->getAdapter()->fetchRow($issue->select()->where('id = ?',$issueId));
		//Zend_Debug::dump($issueData);
		
		$nodeAssocData = $nodeAssociation->getAdapter()->fetchAll($nodeAssociation->select()
								->from('nodeassociation','sink_node_id')
								->where('source_node_id = ?',$issueId)
								->where('association_type = "IssueComponent"'));
		$componentsData = array();
		foreach ($nodeAssocData as $nodeAssoc) {
			$componentsData[] = $nodeAssoc['sink_node_id'];
		}
		$issueData['components'] = $componentsData;
		
		$nodeAssocVersionData = $nodeAssociation->getAdapter()->fetchAll($nodeAssociation->select()
								->from('nodeassociation','sink_node_id')
								->where('source_node_id = ?',$issueId)
								->where('association_type = "IssueVersion"'));
		$versionsData = array();
		foreach ($nodeAssocVersionData as $nodeVersionAssoc) {
			$versionsData[] = $nodeVersionAssoc['sink_node_id'];
		}
		$issueData['affectVersions'] = $versionsData;
		
		$fixVersionData = $nodeAssociation->getAdapter()->fetchAll($nodeAssociation->select()
								->from('nodeassociation','sink_node_id')
								->where('source_node_id = ?',$issueId)
								->where('association_type = "IssueFixVersion"'));
		$fixVersionsData = array();
		foreach ($fixVersionData as $fixVersion) {
			$fixVersionsData[] = $fixVersion['sink_node_id'];
		}
		$issueData['fixVersions'] = $fixVersionsData;
		
		$form->populate($issueData);
		
		$iData = $issue->getIssueRow($issueId);
		//$form->populate($nodeAssocData);
		$priority = new Priority();
		$priorityList = $priority->getList();
		
		$this->view->priorityList = $priorityList;
		$this->view->data = $iData;
		$this->view->form = $form;
		$this->view->issueId = $issueId;
	}
	
	public function closeAction()
	{
		//$form = new CloseIssueForm1();
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		
		$id = $this->_getParam('id');
		$issue = new Issue();
		
		if ($issue->getStatus($id) == 'Closed') {
			$this->_redirect('issue/invalid/id/'.$id);
		}
		
		$changeItem = new ChangeItem();
		$resolution = new Resolution();
		$issueStatus = new IssueStatus();
		$nodeAssociation = new NodeAssociation();
		$action = new Action();
		$projectVersion = new ProjectVersion();
		$changeGroup = new ChangeGroup();
		$userBase = new UserBase();
		
		$iData = $issue->getIssueRow($id);
		//$iData['issueStatusName'] = 'Resolved';
		if ($iData['issueStatusName'] == 'Resolved') {
			$form = new CloseIssueForm2();
		} else {
			$form = new CloseIssueForm1();
		}
		//Zend_Debug::dump($iData);
		if ($this->getRequest()->isPost()) {
			$formData = $this->_request->getPost();
			if ($form->isValid($formData)) {
				//Zend_Debug::dump($formData);exit;
				$id = $formData['id'];
				if (isset($formData['resolution'])) {
					$oldResolutionValue = $issue->getAdapter()->fetchOne($issue->select()
														->from('issue','resolution')
														->where('id = ?',$id));
					if ($oldResolutionValue) {
						$oldResolutionString = $resolution->getAdapter()
														->fetchOne($resolution->select()
															->from('resolution','pname')
															->where('id = ?',$oldResolutionValue));
					} else {
						$oldResolution = null;
					}
					//echo 'this is resss';exit;
					$resolutionRow = $resolution->getAdapter()
										->fetchRow($resolution->select()
														->from('resolution',array('id','pname'))
														->where('id = ?',$formData['resolution']));
					$newResolutionValue = $resolutionRow['id'];
					$newResolutionString = $resolutionRow['pname'];
					$groupData = array(
							'issueid' => $id,
							'author' => $userInfo->fullname,
							'created' => new Zend_Db_Expr('NOW()')
					);
					
					$changeGroup->insert($groupData);
					$groupId = $changeGroup->getAdapter()->lastInsertId();
					// for chaging resolution
					$changeItemData = array(
							'groupid' => $groupId,
							'fieldtype' => 'ppmis',
							'field' => 'resolution',
							'oldvalue' => $oldResolutionValue,
							'oldstring' => $oldResolutionString,
							'newvalue' => $newResolutionValue,
							'newstring' => $newResolutionString
					);
					
					// Insert values in issuechange table
					$changeItem->insert($changeItemData);
				} // end formData['resolution']
				
				if(!$groupId) {
					$groupData = array(
							'issueid' => $id,
							'author' => $userInfo->fullname,
							'created' => new Zend_Db_Expr('NOW()')
					);
					
					$changeGroup->insert($groupData);
					$groupId = $changeGroup->getAdapter()->lastInsertId();
				}
				// code for updating status.....
				$oldStatusValue = $issue->getAdapter()->fetchOne($issue->select()
														->from('issue','issuestatus')
														->where('id = ?',$id));
				$oldStatusString = $issueStatus->getAdapter()->fetchOne($issueStatus->select()
														->from('issuestatus','pname')
														->where('id = ?',$oldStatusValue));
				$statusRow = $issueStatus->getAdapter()
									->fetchRow($issueStatus->select()
													->from('issuestatus',array('id','pname'))
													->where('pname = ?','Closed'));
				$newStatusValue = $statusRow['id'];
				$newStatusString = $statusRow['pname'];
				
				// updating issue resolution
				$issueData = array();
				$issueData['issuestatus'] =  $newStatusValue;
				
				if($formData['assignee']) {
					$oldAssignee = $issue->getAdapter()->fetchOne($issue->select()
												->from('issue','assignee')
												->where('id = ?',$id));
					$oldAssigneeValue = $userBase->getUserByFullname($oldAssignee);
					if($formData['assignee'] == $oldAssignee) {
						// if submitted assignee and old assignee are same do nothing
					} else {
						$newAssigneeValue = $userBase->getUserByFullname($formData['assignee']);
						
						$issueData['assignee'] = $formData['assignee'];
						
						$changeItemData = array(
								'groupid' => $groupId,
								'fieldtype' => 'ppmis',
								'field' => 'assignee',
								'oldvalue' => $oldAssigneeValue,
								'oldstring' => $oldAssignee,
								'newvalue' => $newAssigneeValue,
								'newstring' => $formData['assignee']
						);
					
						$changeItem->insert($changeItemData);
						
					}
				}
				
				if ($newResolutionValue) {
					$issueData['resolution'] =  $newResolutionValue;
				}
				$issueData['updated'] = new Zend_Db_Expr('NOW()');
				
				$issue->update($issueData, "id = $id");
				
				$changeItemData = array(
						'groupid' => $groupId,
						'fieldtype' => 'ppmis',
						'field' => 'status',
						'oldvalue' => $oldStatusValue,
						'oldstring' => $oldStatusString,
						'newvalue' => $newStatusValue,
						'newstring' => $newStatusString
				);
				//Zend_Debug::dump($changeItemData);exit;
				$changeItem->insert($changeItemData);
				
				if ($formData['comments']) {
					$action->insert(array(
							'issueid' => $id,
							'author' => $userInfo->fullname,
							'action_type' => 'comment',
							'action_body' => $formData['comments'],
							'created' => new Zend_Db_Expr('NOW()')
					));
				}
				
				// code for fix version
				if (isset($formData['fixVersion']))	{
					$where = "source_node_id = '". $formData['id']."' AND association_type = 'IssueFixVersion'";
					$oldFixVersions = $nodeAssociation->getAdapter()->fetchAll($nodeAssociation->select()
														->from('nodeassociation','sink_node_id')
														->where($where));
					$oldFixVersionData = array();
					foreach ($oldFixVersions as $v) {
						$oldFixVersionData[] = $v['sink_node_id'];
					}
					$where = "source_node_id = '". $formData['id']."' AND association_type = 'IssueFixVersion'";
					$nodeAssociation->delete($where);
					foreach($formData['fixVersion'] as $fixVersionId) {
						if (in_array($fixVersionId, $oldFixVersionData)) {
							$versionData = array(
								'source_node_id' => $formData['id'],
								'source_node_entity' => 'Issue',
								'sink_node_id' => $fixVersionId,
								'sink_node_entity' => 'Fix Version',
								'association_type' => 'IssueFixVersion'
							);
						
							$nodeAssociation->insert($versionData);
						} else {
							$versionRow = $projectVersion->getAdapter()
														->fetchRow($projectVersion->select()
														->from('projectversion',array('id','vname'))
														->where('id = ?',$fixVersionId));
							$changeItemData = array(
								'groupid' => $groupId,
								'fieldtype' => 'ppmis',
								'field' => 'Fix Version',
								'newvalue' => $versionRow['id'],
								'newstring' => $versionRow['vname']
							);
							$changeItem->insert($changeItemData);
							
							$versionData = array(
								'source_node_id' => $formData['id'],
								'source_node_entity' => 'Issue',
								'sink_node_id' => $fixVersionId,
								'sink_node_entity' => 'Fix Version',
								'association_type' => 'IssueFixVersion'
							);
						
							$nodeAssociation->insert($versionData);
						}
					}
					
					foreach ($oldFixVersionData as $oldFixVersion) {
					if (in_array($oldFixVersion, $formData['fixVersion'])) {
					} else {
						$fixVersionName = $projectVersion->getAdapter()->fetchOne($projectVersion->select()
														->from('projectversion','vname')
														->where('id = ?', $oldFixVersion));
							$changeItemData = array(
								'groupid' => $groupId,
								'fieldtype' => 'ppmis',
								'field' => 'Fix Version',
								'oldvalue' => $oldFixVersion,
								'oldstring' => $fixVersionName
							);
							$changeItem->insert($changeItemData);
						}
					} // end of old fix version handling.....
					
					$this->_redirect('issue/view/id/'.$id);
				}
			}
		}	
		$fixVersionData = $nodeAssociation->getAdapter()->fetchAll($nodeAssociation->select()
								->from('nodeassociation','sink_node_id')
								->where('source_node_id = ?',$id)
								->where('association_type = "IssueFixVersion"'));
		
		$fixVersionsData = array();
		foreach ($fixVersionData as $fixVersion) {
			$fixVersionsData[] = $fixVersion['sink_node_id'];
		}
		$issueData['fixVersion'] = $fixVersionsData;
		$form->populate($issueData);
		$this->view->data = $iData;
		$this->view->form = $form;
	}
	
	public function resolveAction()
	{
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		
		$id = $this->_getParam('id');
		$issue = new Issue();
		// check if issue has already been resolved
		if ($issue->getStatus($id) == 'Resolved') {
			$this->_redirect('issue/invalid/id/'.$id);
		}
		$form = new ResolveIssueForm();
		$changeItem = new ChangeItem();
		$resolution = new Resolution();
		$issueStatus = new IssueStatus();
		$action = new Action();
		$changeGroup = new ChangeGroup();
		$nodeAssociation = new NodeAssociation();
		$projectVersion = new ProjectVersion();
		$userBase = new UserBase();
		
		if ($this->getRequest()->isPost()) {
			$formData = $this->_request->getPost();
			if ($form->isValid($formData)) {
				$issueData = array();
				$id = $formData['id'];
				$oldResolutionValue = $issue->getAdapter()->fetchOne($issue->select()
														->from('issue','resolution')
														->where('id = ?',$id));
				if ($oldResolutionValue) {
					$oldResolutionString = $resolution->getAdapter()
													->fetchOne($resolution->select()
														->from('resolution','pname')
														->where('id = ?',$oldResolutionValue));
				} else {
					$oldResolution = null;
				}
				$resolutionRow = $resolution->getAdapter()
									->fetchRow($resolution->select()
													->from('resolution',array('id','pname'))
													->where('id = ?',$formData['resolution']));
				$newResolutionValue = $resolutionRow['id'];
				$issueData['resolution'] = $newResolutionValue; 
				$newResolutionString = $resolutionRow['pname'];
				$groupData = array(
						'issueid' => $id,
						'author' => $userInfo->fullname,
						'created' => new Zend_Db_Expr('NOW()')
				);
				
				$changeGroup->insert($groupData);
				$groupId = $changeGroup->getAdapter()->lastInsertId();
				// for chaging resolution
				$changeItemData = array(
						'groupid' => $groupId,
						'fieldtype' => 'ppmis',
						'field' => 'resolution',
						'oldvalue' => $oldResolutionValue,
						'oldstring' => $oldResolutionString,
						'newvalue' => $newResolutionValue,
						'newstring' => $newResolutionString
				);
				
				// Insert values in issuechange table
				$changeItem->insert($changeItemData);
								
				// for change status
				$oldStatusValue = $issue->getAdapter()->fetchOne($issue->select()
														->from('issue','issuestatus')
														->where('id = ?',$id));
				$oldStatusString = $issueStatus->getAdapter()->fetchOne($issueStatus->select()
														->from('issuestatus','pname')
														->where('id = ?',$oldStatusValue));
				$statusRow = $issueStatus->getAdapter()
									->fetchRow($issueStatus->select()
													->from('issuestatus',array('id','pname'))
													->where('pname = ?','Resolved'));
				$newStatusValue = $statusRow['id'];
				$issueData['issuestatus'] = $newStatusValue;
				$newStatusString = $statusRow['pname'];
				
				if($formData['assignee']) {
					$oldAssignee = $issue->getAdapter()->fetchOne($issue->select()
												->from('issue','assignee')
												->where('id = ?',$id));
					$oldAssigneeValue = $userBase->getUserByFullname($oldAssignee);
					if($formData['assignee'] == $oldAssignee) {
						// if submitted assignee and old assignee are same do nothing
					} else {
						$newAssigneeValue = $userBase->getUserByFullname($formData['assignee']);
						
						$issueData['assignee'] = $formData['assignee'];
						
						$changeItemData = array(
								'groupid' => $groupId,
								'fieldtype' => 'ppmis',
								'field' => 'assignee',
								'oldvalue' => $oldAssigneeValue,
								'oldstring' => $oldAssignee,
								'newvalue' => $newAssigneeValue,
								'newstring' => $formData['assignee']
						);
					
						$changeItem->insert($changeItemData);
						
					}
				}
				
				$issueData['updated'] = new Zend_Db_Expr('NOW()');
				// updating issue resolution
				$issue->update($issueData,"id = $id");
				
				$changeItemData = array(
						'groupid' => $groupId,
						'fieldtype' => 'ppmis',
						'field' => 'status',
						'oldvalue' => $oldStatusValue,
						'oldstring' => $oldStatusString,
						'newvalue' => $newStatusValue,
						'newstring' => $newStatusString
				);
				$changeItem->insert($changeItemData);
				
				// inserting values in action for if comments posted
				if ($formData['comments']) {
					$action->insert(array(
							'issueid' => $id,
							'author' => $userInfo->fullname,
							'action_type' => 'comment',
							'action_body' => $formData['comments'],
							'created' => new Zend_Db_Expr('NOW()')
					));
				}
				
				// code for fix version
				$where = "source_node_id = '". $formData['id']."' AND association_type = 'IssueFixVersion'";
				$oldFixVersions = $nodeAssociation->getAdapter()->fetchAll($nodeAssociation->select()
														->from('nodeassociation','sink_node_id')
														->where($where));
				$oldFixVersionData = array();
				foreach ($oldFixVersions as $v) {
					$oldFixVersionData[] = $v['sink_node_id'];
				}
				$where = "source_node_id = '". $formData['id']."' AND association_type = 'IssueFixVersion'";
				$nodeAssociation->delete($where);
				foreach($formData['fixVersion'] as $fixVersionId) {
					if (in_array($fixVersionId, $oldFixVersionData)) {
						$versionData = array(
							'source_node_id' => $formData['id'],
							'source_node_entity' => 'Issue',
							'sink_node_id' => $fixVersionId,
							'sink_node_entity' => 'Fix Version',
							'association_type' => 'IssueFixVersion'
						);
					
						$nodeAssociation->insert($versionData);
					} else {
						$versionRow = $projectVersion->getAdapter()
													->fetchRow($projectVersion->select()
													->from('projectversion',array('id','vname'))
													->where('id = ?',$fixVersionId));
						$changeItemData = array(
							'groupid' => $groupId,
							'fieldtype' => 'ppmis',
							'field' => 'Fix Version',
							'newvalue' => $versionRow['id'],
							'newstring' => $versionRow['vname']
						);
						$changeItem->insert($changeItemData);
						
						$versionData = array(
							'source_node_id' => $formData['id'],
							'source_node_entity' => 'Issue',
							'sink_node_id' => $fixVersionId,
							'sink_node_entity' => 'Fix Version',
							'association_type' => 'IssueFixVersion'
						);
					
						$nodeAssociation->insert($versionData);
					}
				}
				
				foreach ($oldFixVersionData as $oldFixVersion) {
					if (in_array($oldFixVersion, $formData['fixVersion'])) {
					} else {
						$fixVersionName = $projectVersion->getAdapter()->fetchOne($projectVersion->select()
														->from('projectversion','vname')
														->where('id = ?', $oldFixVersion));
						$changeItemData = array(
							'groupid' => $groupId,
							'fieldtype' => 'ppmis',
							'field' => 'Fix Version',
							'oldvalue' => $oldFixVersion,
							'oldstring' => $fixVersionName
						);
						$changeItem->insert($changeItemData);
					}
				} // end of old fix version handling.....
				
				$this->_redirect('issue/view/id/'.$id);
			}
		}
		//$issueData = array();
		$fixVersionData = $nodeAssociation->getAdapter()->fetchAll($nodeAssociation->select()
								->from('nodeassociation','sink_node_id')
								->where('source_node_id = ?',$id)
								->where('association_type = "IssueFixVersion"'));
		
		$fixVersionsData = array();
		foreach ($fixVersionData as $fixVersion) {
			$fixVersionsData[] = $fixVersion['sink_node_id'];
		}
		$issueData['fixVersion'] = $fixVersionsData;
		$iData = $issue->getIssueRow($id);
		$this->view->data = $iData;
		$form->populate($issueData);
		$this->view->form = $form;
	}
	
	public function reopenAction()
	{
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		
		$id = $this->_getParam('id');
		$issue = new Issue();
		
		if ($issue->getStatus($id) == 'Open') {
			$this->_redirect('issue/invalid/id/'.$id);
		}
		
		$form = new ReopenIssueForm();
		$action = new Action();
		$changeGroup = new ChangeGroup();
		$changeItem = new ChangeItem();
		$issueStatus = new IssueStatus();
		
		$iData = $issue->getIssueRow($id);
		if ($this->getRequest()->isPost()) {
			$formData = $this->_request->getPost();
			if ($form->isValid($formData)) {
				$id = $formData['id'];
				$groupData = array(
							'issueid' => $id,
							'author' => $userInfo->fullname,
							'created' => new Zend_Db_Expr('NOW()')
					);
					
				$changeGroup->insert($groupData);
				$groupId = $changeGroup->getAdapter()->lastInsertId();
				
				$oldStatusValue = $issue->getAdapter()->fetchOne($issue->select()
														->from('issue','issuestatus')
														->where('id = ?',$id));
				$oldStatusString = $issueStatus->getAdapter()->fetchOne($issueStatus->select()
														->from('issuestatus','pname')
														->where('id = ?',$oldStatusValue));
				$statusRow = $issueStatus->getAdapter()
									->fetchRow($issueStatus->select()
													->from('issuestatus',array('id','pname'))
													->where('pname = ?','Open'));
				$newStatusValue = $statusRow['id'];
				$newStatusString = $statusRow['pname'];
				
				$issue->update(array(
						'issuestatus' => $newStatusValue,
						'updated' => new Zend_Db_Expr('NOW()')
					), "id = $id");
				
				$changeItemData = array(
						'groupid' => $groupId,
						'fieldtype' => 'ppmis',
						'field' => 'status',
						'oldvalue' => $oldStatusValue,
						'oldstring' => $oldStatusString,
						'newvalue' => $newStatusValue,
						'newstring' => $newStatusString
				);
				//Zend_Debug::dump($changeItemData);exit;
				$changeItem->insert($changeItemData);
				
				if ($formData['comments']) {
					$action->insert(array(
							'issueid' => $id,
							'author' => $userInfo->fullname,
							'action_type' => 'comment',
							'action_body' => $formData['comments'],
							'created' => new Zend_Db_Expr('NOW()')
					));
				}
				$this->_redirect('issue/view/id/'.$id);
			}
		}
		$this->view->data = $iData;
		$this->view->form = $form;
	}
	
	public function startprogressAction()
	{
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
		
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		
		$id = $this->_getParam('id');
		$issue = new Issue();
		if ($issue->getStatus($id) == 'In Progress') {
			$this->_redirect('issue/invalid/id/'.$id);
		}
		$action = new Action();
		$changeGroup = new ChangeGroup();
		$changeItem = new ChangeItem();
		$issueStatus = new IssueStatus();
		
		$groupData = array(
							'issueid' => $id,
							'author' => $userInfo->fullname,
							'created' => new Zend_Db_Expr('NOW()')
					);
					
		$changeGroup->insert($groupData);
		$groupId = $changeGroup->getAdapter()->lastInsertId();
		
		$oldStatusValue = $issue->getAdapter()->fetchOne($issue->select()
												->from('issue','issuestatus')
												->where('id = ?',$id));
		$oldStatusString = $issueStatus->getAdapter()->fetchOne($issueStatus->select()
												->from('issuestatus','pname')
												->where('id = ?',$oldStatusValue));
		$statusRow = $issueStatus->getAdapter()
							->fetchRow($issueStatus->select()
											->from('issuestatus',array('id','pname'))
											->where('pname = ?','In Progress'));
		$newStatusValue = $statusRow['id'];
		$newStatusString = $statusRow['pname'];
		
		$issue->update(array(
				'issuestatus' => $newStatusValue,
				'updated' => new Zend_Db_Expr('NOW()')
			), "id = $id");
		
		$changeItemData = array(
				'groupid' => $groupId,
				'fieldtype' => 'ppmis',
				'field' => 'status',
				'oldvalue' => $oldStatusValue,
				'oldstring' => $oldStatusString,
				'newvalue' => $newStatusValue,
				'newstring' => $newStatusString
		);
		//Zend_Debug::dump($changeItemData);exit;
		$changeItem->insert($changeItemData);
		$this->_redirect('issue/view/id/'.$id);
	}
	
	public function stopprogressAction()
	{
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
		
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		
		$id = $this->_getParam('id');
		$issue = new Issue();
		if ($issue->getStatus($id) == 'Open') {
			$this->_redirect('issue/invalid/id/'.$id);
		}
		$action = new Action();
		$changeGroup = new ChangeGroup();
		$changeItem = new ChangeItem();
		$issueStatus = new IssueStatus();
		
		$groupData = array(
							'issueid' => $id,
							'author' => $userInfo->fullname,
							'created' => new Zend_Db_Expr('NOW()')
					);
					
		$changeGroup->insert($groupData);
		$groupId = $changeGroup->getAdapter()->lastInsertId();
		
		$oldStatusValue = $issue->getAdapter()->fetchOne($issue->select()
												->from('issue','issuestatus')
												->where('id = ?',$id));
		$oldStatusString = $issueStatus->getAdapter()->fetchOne($issueStatus->select()
												->from('issuestatus','pname')
												->where('id = ?',$oldStatusValue));
		$statusRow = $issueStatus->getAdapter()
							->fetchRow($issueStatus->select()
											->from('issuestatus',array('id','pname'))
											->where('pname = ?','Open'));
		$newStatusValue = $statusRow['id'];
		$newStatusString = $statusRow['pname'];
		
		$issue->update(array(
				'issuestatus' => $newStatusValue,
				'updated' => new Zend_Db_Expr('NOW()')
			), "id = $id");
		
		$changeItemData = array(
				'groupid' => $groupId,
				'fieldtype' => 'ppmis',
				'field' => 'status',
				'oldvalue' => $oldStatusValue,
				'oldstring' => $oldStatusString,
				'newvalue' => $newStatusValue,
				'newstring' => $newStatusString
		);
		//Zend_Debug::dump($changeItemData);exit;
		$changeItem->insert($changeItemData);
		$this->_redirect('issue/view/id/'.$id);
	}
	
	public function cloneAction()
	{
		$id = $this->_getParam('id');
		$issue = new Issue();
		$nodeAssoc = new NodeAssociation();
		$form = new CloneIssueForm();
		$summary = $issue->getAdapter()->fetchOne($issue->select()
														->from('issue','summary')
														->where('id = ?', $id));
		$summary = array('summary' => 'CLONE -'.$summary);
		$form->populate($summary);
		if ($this->getRequest()->isPost()) {
			$formData = $this->_request->getPost();
			if ($form->isValid($formData)) {
				$id = $formData['id'];
				$iData = $issue->getAdapter()->fetchRow($issue->select()->where('id = ?', $id));
				unset($iData['id']);
				$iData['summary'] = $formData['summary'];
				//Zend_Debug::dump($iData);
				$issue->insert($iData);
				$issueId = $issue->getAdapter()->lastInsertId();
				$nodeAssocData = $nodeAssoc->getAdapter()->fetchAll($nodeAssoc->select()->where('source_node_id = ?', $id));
				//Zend_Debug::dump($nodeAssocData);
				for ($i = 0; $i < count($nodeAssocData); $i++) {
					$nodeAssocData[$i]['source_node_id'] = $issueId;
					$nodeAssoc->insert($nodeAssocData[$i]);
				}
				//Zend_Debug::dump($nodeAssocData);
				$this->_redirect('issue/view/id/'.$issueId);
			}
		}
		$this->view->form = $form;
	}
	
	public function assignAction()
	{
		$id = $this->_getParam('id');
		
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		
		$issue = new Issue();
		$changeItem = new ChangeItem();
		$issueStatus = new IssueStatus();
		$action = new Action();
		$changeGroup = new ChangeGroup();
		$userBase = new UserBase();
		
		$iData = $issue->getIssueRow($id);
		$form = new AssignIssueForm();
		if ($this->getRequest()->isPost()) {
			$formData = $this->_request->getPost();
			if ($form->isValid($formData)) {
				$oldAssignee = $issue->getAdapter()->fetchOne($issue->select()
												->from('issue','assignee')
												->where('id = ?',$id));
				
				$oldAssigneeValue = $userBase->getUserByFullname($oldAssignee);
				
				/*$oldAssigneeValue = $users->getAdapter()->fetchOne($users->select()
														->from('users','uid')
														->where('fullname=?',$oldAssignee));*/
				// if assignee is not changed
				if($formData['assignee'] == $oldAssignee) {
					// do nothing	
				} else {
					$newAssigneeValue = $userBase->getUserByFullname($formData['assignee']);
					/*$newAssigneeValue = $users->getAdapter()->fetchOne($users->select()
														->from('users','uid')
														->where('fullname=?',$formData['assignee']));*/
					
					$issue->update(array(
								'assignee' => $formData['assignee'],
								'updated' => new Zend_Db_Expr('NOW()')
							), "id = $id");
					
					$groupData = array(
							'issueid' => $id,
							'author' => $userInfo->fullname,
							'created' => new Zend_Db_Expr('NOW()')
					);
					
					$changeGroup->insert($groupData);
					$groupId = $changeGroup->getAdapter()->lastInsertId();
					
					$changeItemData = array(
								'groupid' => $groupId,
								'fieldtype' => 'ppmis',
								'field' => 'assignee',
								'oldvalue' => $oldAssigneeValue,
								'oldstring' => $oldAssignee,
								'newvalue' => $newAssigneeValue,
								'newstring' => $formData['assignee']
						);
					
					$changeItem->insert($changeItemData);
				}
				
				if ($formData['comments']) {
					$action->insert(array(
							'issueid' => $id,
							'author' => $userInfo->fullname,
							'action_type' => 'comment',
							'action_body' => $formData['comments'],
							'created' => new Zend_Db_Expr('NOW()')
					));
				}
				
				$this->_redirect('issue/view/id/'.$id);
			}
		}
		$this->view->data = $iData;
		$this->view->form = $form;
	}
	
	public function changestatusAction()
	{
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		
		$form = new ChangeIssueStatusForm();
		$id = $this->_getParam('id',1);
		$issueChange = new IssueChange();
		$issueStatus = new IssueStatus();
		$issue = new Issue();
		$action = new Action();
		$oldValue = $issue->getAdapter()->fetchOne($issue->select()
														->from('issue','issuestatus')
														->where('id',$id));
		
		if ($this->getRequest()->isPost()) {
			$formData = $this->_request->getPost();
			if ($form->isValid($formData)) {
				$newValue = $issueStatus->getAdapter()
									->fetchOne($issueStatus->select()
														->from('issuestatus','pname')
														->where('id = ?',$formData['status']));
				echo $newValue;
				$data = array(
						'issueid' => $id,
						'author' => $userInfo->fullname,
						'field' => 'issuestatus',
						'oldvalue' => $oldValue,
						'newvalue' => $newValue,
						'time' => new Zend_Db_Expr('NOW()')
				);
				Zend_Debug::dump($data);
				// Insert values in issuechange table
				//$issueChange->insert($data);
				// update issue table resolution
				/*$issue->update(array(
					'issuestatus' => $newValue,
					'updated' => new Zend_Db_Expr('NOW()')
				),"id = $id");*/
				
				// inserting values in action for if comments posted
				/*if ($formData['comments']) {
					$action->update(array(
							'issueid' => $id,
							'author' => 'Faheem',
							'action_type' => 'comment',
							'action_body' => $formData['comments'],
							'created' => new Zend_Db_Expr('NOW()')
					));
				}*/
			}
		}
		$this->view->form = $form;
	}
	
	public function changepriorityAction()
	{
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		
		$form = new ChangeIssuePriorityForm();
		$id = $this->_getParam('id',1);
		$issueChange = new IssueChange();
		$priority = new Priority();
		$issue = new Issue();
		$action = new Action();
		$oldValue = $issue->getAdapter()->fetchOne($issue->select()
														->from('issue','priority')
														->where('id=?',$id));
		
		if ($this->getRequest()->isPost()) {
			$formData = $this->_request->getPost();
			if ($form->isValid($formData)) {
				$newValue = $priority->getAdapter()
									->fetchOne($priority->select()
														->from('priority','pname')
														->where('id = ?',$formData['priority']));
				$data = array(
						'issueid' => $id,
						'author' => $userInfo->fullname,
						'field' => 'priority',
						'oldvalue' => $oldValue,
						'newvalue' => $newValue,
						'time' => new Zend_Db_Expr('NOW()')
				);
				Zend_Debug::dump($data);
				// Insert values in issuechange table
				//$issueChange->insert($data);
				// update issue table resolution
				/*$issue->update(array(
					'priority' => $newValue,
					'updated' => new Zend_Db_Expr('NOW()')
				),"id = $id");*/
				
				// inserting values in action for if comments posted
				/*if ($formData['comments']) {
					$action->update(array(
							'issueid' => $id,
							'author' => 'Faheem',
							'action_type' => 'comment',
							'action_body' => $formData['comments'],
							'created' => new Zend_Db_Expr('NOW()')
					));
				}*/
			}
		}
		$this->view->form = $form;
	}
	
	public function componentsAction()
	{
		$this->view->current = 'project';
		$this->view->current = "project";
		$projectId = $this->_getParam('project');
		$project = new Project();
		$component = new Component();
		$issue  = new Issue();
		$projectData = $project->getAdapter()->fetchRow($project->select()->where('id=?',$projectId));
		$data = $component->getAdapter()->fetchAll($component->select()->where('project = ?', $projectId));
		
		/*$projectSummary = $issue->getAdapter()->fetchAll($issue->select()
														->from('issue',array("issuestatus","count(*) As c"))
														->group('issuestatus'));
														
		$openIssues = $issue->getAdapter()->fetchAll($issue->select()
														->from('issue',array("priority","count(*) As c"))
														->group('priority'));
														
		$totalIssues = $issue->getAdapter()->fetchOne($issue->select()
																->from('issue',"count(*)"));*/
		$projectSummary = $issue->getIssueSummaryData($projectId);												
		$openIssues = $issue->getOpenIssuesData($projectId);
		$openIssuesByAssignee = $issue->getOpenIssuesByAssignee($projectId);
		
		$totalIssues = $issue->numRows($projectId);
														
		$this->view->projectData = $projectData;
		$this->view->totalIssues = $totalIssues;
		$this->view->projectSummary = $projectSummary;
		$this->view->openIssues = $openIssues;
		$this->view->openIssuesByAssignee = $openIssuesByAssignee;
		$this->view->components = $data;
		$this->view->projectId = $projectId;
	}
	public function openissuesAction()
	{
		$this->view->current = "project";
		$pid = $this->_getParam('pid');
		$project = new Project();
		$issue  = new Issue();
		$component = new Component();
		$components = $component->getData($pid);
		
		$projectVersion = new ProjectVersion();
		$versionsData = $projectVersion->getData($pid);
		
		$projectData = $project->getAdapter()->fetchRow($project->select()->where('id=?',$pid));
		
		$projectSummary = $issue->getIssueSummaryData($pid);												
		$openIssues = $issue->getOpenIssuesData($pid);
		$openIssuesByAssignee = $issue->getOpenIssuesByAssignee($pid);
														
		$totalIssues = $issue->numRows($pid);
																
		$unscheduledIssues = $issue->getUnscheduledIssues($pid);
		$noComponentIssues = $issue->getNoComponentIssues($pid);
		
		$this->view->noComponentIssues = $noComponentIssues;
		$this->view->unscheduleIssues = $unscheduledIssues;
		$this->view->projectData = $projectData;
		$this->view->totalIssues = $totalIssues;
		$this->view->projectSummary = $projectSummary;
		$this->view->openIssuesByAssignee = $openIssuesByAssignee;
		$this->view->openIssues = $openIssues;
		$this->view->components = $components;
		$this->view->versionsData = $versionsData;
		$this->view->projectId = $pid;
	}
	
	public function roadmapAction()
	{
		$this->view->current = 'project';
		$projectId = $this->_getParam('project');
		$project = new Project();
		$component = new Component();
		$issue  = new Issue();
		
		$projectVersion = new ProjectVersion();
		$projectData = $project->getAdapter()->fetchRow($project->select()->where('id=?',$projectId));
		//$data = $component->getAdapter()->fetchAll($component->select()->where('project = ?', $projectId));
		
		$projectSummary = $issue->getIssueSummaryData($projectId);												
		$openIssues = $issue->getOpenIssuesData($projectId);
		$openIssuesByAssignee = $issue->getOpenIssuesByAssignee($projectId);
		$totalIssues = $issue->numRows($projectId);
		
		$allVersion = $projectVersion->getProjectVersion($projectId);
		
		//Zend_Debug::dump($allVersion);
		$i = 0;
		foreach ($allVersion as $version) {
			$allVersion[$i]['issues'] = $issue->getVersionIssues($version['id']);
			$j = 0;
			$unresolvedIssues = 0;
			foreach ($allVersion[$i]['issues'] as $issues) {
			//Zend_Debug::dump($issues['resolutionName']);
				if (!$issues['resolutionName']) {
					$allVersion[$i]['issues'][$j]['resolutionName'] = '<font style="color:red">Unresolved</font>';
					$unresolvedIssues++;
				}
				$j++;
			}
			$allVersion[$i]['totalIssues'] = count($allVersion[$i]['issues']);
			$allVersion[$i]['unresolvedIssues'] = $unresolvedIssues;
			$allVersion[$i]['resolvedIssues'] = count($allVersion[$i]['issues']) - $unresolvedIssues;
			$i++;
		}
		//Zend_Debug::dump($allVersion);
		$this->view->projectData = $projectData;
		$this->view->totalIssues = $totalIssues;
		$this->view->projectSummary = $projectSummary;
		$this->view->openIssues = $openIssues;
		$this->view->openIssuesByAssignee = $openIssuesByAssignee;
		$this->view->versionData = $allVersion;
		//$this->view->components = $data;
		$this->view->projectId = $projectId;
	}
	
	public function versionsAction()
	{
		$this->view->current = 'project';
		$projectId = $this->_getParam('projectId');
		$project = new Project();
		$projectVersion = new ProjectVersion();
		$issue  = new Issue();
		
		$projectData = $project->getAdapter()->fetchRow($project->select()->where('id=?',$projectId));
		
		$versions = $projectVersion->getProjectVersion($projectId);
		$projectSummary = $issue->getIssueSummaryData($projectId);												
		$openIssues = $issue->getOpenIssuesData($projectId);
		$openIssuesByAssignee = $issue->getOpenIssuesByAssignee($projectId);
		
		$totalIssues = $issue->numRows($projectId);
		
		$this->view->projectData = $projectData;
		$this->view->totalIssues = $totalIssues;
		$this->view->projectSummary = $projectSummary;
		$this->view->openIssues = $openIssues;
		$this->view->openIssuesByAssignee = $openIssuesByAssignee;
		$this->view->versions = $versions;
		$this->view->projectId = $projectId;
	}
	
	public function linkAction()
	{
		$id = $this->_getParam('id');
		$issue = new Issue();
		$issueLink = new IssueLink();
		$form = new IssueLinkForm();
		$iData = $issue->getIssueRow($id);
		
		if ($this->getRequest()->isPost()) {
			$formData = $this->_request->getPost();
			if ($form->isValid($formData)) {
				$pkeys = explode(',', $formData['destination']);
				foreach ($pkeys as $pkey) {
					$issueId = $issue->getAdapter()->fetchOne($issue->select()
													->from('issue','id')
													->where('pkey = ?', $pkey));
					if ($issueId == $formData['id']) {	
						
					} else {
						// for the current issue
						$linkData = array(
								'linktype' => $formData['linktype'],
								'source' => $formData['id'],
								'destination' => $issueId
						);
						$issueLink->insert($linkData);
						
						// for the other issues
						if ($formData['linktype'] == 1) {
							$linkType = 2;
						} else {
							$linkType = 1;
						} 
						$linkData = array(
								'linktype' => $linkType,
								'source' => $issueId,
								'destination' => $formData['id']
						);
						$issueLink->insert($linkData);
					}
				}
			}
			$this->_redirect('issue/view/id/'.$id);
		}
		
		$this->view->data = $iData;
		$this->view->form = $form;
	}
	
	public function attachmentAction()
	{
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		$id = $this->_getParam('id');
		$issue = new Issue();
		$action = new Action();
		$project = new Project();
		$fileAttachment = new FileAttachment();
		$changeGroup = new ChangeGroup();
		$changeItem = new ChangeItem();
		
		$form = new AttachFileForm();
		$iData = $issue->getIssueRow($id);
		$projectKey = $project->getAdapter()->fetchOne($project->select()
											->from('project','pkey')
											->where("id = (SELECT project FROM issue
														WHERE id = $id)"));
		if ($this->getRequest()->isPost()) {
			//$formData = $this->_request->getPost();
			if ($form->isValid($_POST)) {
				$basePath = $this->getRequest()->getBaseUrl();
				$file = $_FILES['attachment1'];
				$attachmentData = array(
						'issueid' => $id,
						'mimetype' => $file['type'],
						'filename' => $file['name'],
						'created' => new Zend_Db_Expr('NOW()'),
						'filesize' => $file['size'],
						'author' => $userInfo->fullname
				);
				$fileAttachment->insert($attachmentData);
				$attachmentId= $fileAttachment->getAdapter()->lastInsertId();
				if (!is_dir('../public/uploads/'.$projectKey)) {
					mkdir('../public/uploads/'.$projectKey);
				}
				$uploadedfile = '../public/uploads/'.$projectKey.'/'.$attachmentId.'_'.$file['name'];
				$adapter=new Zend_File_Transfer_Adapter_Http();
				$adapter->addFilter('Rename',
                   		array('target' => $uploadedfile,
                        	 'overwrite' => true));
				$adapter->setOptions(array('ignoreNoFile'=>true));
				if($adapter->receive()) {
				}
				
				$groupData = array(
						'issueid' => $id,
						'author' => $userInfo->fullname,
						'created' => new Zend_Db_Expr('NOW()')
				);
				$changeGroup->insert($groupData);
				$groupId = $changeGroup->getAdapter()->lastInsertId();
				
				$changeItemData = array(
						'groupid' => $groupId,
						'fieldtype' => 'ppmis',
						'field' => 'Attachment',
						'newvalue' => $attachmentId,
						'newstring' => $file['name']
				);
				
				$changeItem->insert($changeItemData);
				
				if ($this->_getParam('comments')) {
					$action->insert(array(
							'issueid' => $id,
							'author' => $userInfo->fullname,
							'action_type' => 'comment',
							'action_body' =>$this->_getParam('comments'),
							'created' => new Zend_Db_Expr('NOW()')
					));
				}
				$this->_redirect('issue/view/id/'.$id);
				
			}
		}
		
		$this->view->data = $iData;
		$this->view->form = $form;
	}
	
	public function invalidAction()
	{
		$id = $this->_getParam('id');
		$this->view->id = $id;
	}
	function usersAction()
	{
		$userBase = new UserBase();
		$db=Zend_Registry::get('db');
		$query = $this->_getParam('query');
		
		$select = 'SELECT userBase.id, userBase.name, propertyEntry.property_key, propertyString.propertyvalue FROM 
		userbase as userBase INNER JOIN propertyentry as propertyEntry on userBase.id = propertyEntry.entry_id
		INNER JOIN propertystring as propertyString on propertyEntry.id = propertyString.id 
		HAVING userBase.name like "%'.$query.'%"';
		
		$results = $db->fetchAll($select);
		$data = array();
		$i = 0;
		foreach ($results as $result) {
			$data[$i]['username'] = $result['name'];
			if ($result['property_key'] == 'Email') {
				$data[$i]['email'] = $result['propertyvalue'];
			}
			if ($result['property_key'] == 'fullname') {
				$data[$i]['fullname'] = $result['propertyvalue'];
			}	
		}
		$dojoData= new Zend_Dojo_Data('username',$data,'id');
		//echo Zend_Json::encode($result);
        echo $dojoData->toJson();
        exit;
	}
	
	protected function _processXml($data)
	{
		$objReader = XMLReader::XML($data);
			$params = array();
				while ($objReader->read()) {
					if($objReader->nodeType == 1 && $objReader->localName == 'project' && $objReader->hasAttributes) {
						$params['projects'][] = $objReader->getAttribute('id');
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'issuetype' && $objReader->hasAttributes) {
						$params['issuetypes'][] = $objReader->getAttribute('value');
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'query') {
						$query = $objReader->readString();
						$params['query']['text'] = $query;
						if($objReader->getAttribute['summary']) {
							$params['query']['summary'] = true;
						}
						if($objReader->getAttribute['description']) {
							$params['query']['description'] = true;
						}
						if($objReader->getAttribute['comments']) {
							$params['query']['comments'] = true;
						}
						if($objReader->getAttribute['environment']) {
							$params['query']['environment'] = true;
						}
					}
					
					if($objReader->nodeType == 1 && $objReader->localName == 'reporter' && $objReader->hasAttributes) {
						$params['reporter'] = $objReader->getAttribute('key');
						if ($params['reporter'] == 'specify') {
							$params['reporterName'] = $objReader->readString();
						}
					
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'assignee' && $objReader->hasAttributes) {
						$params['assignee'] = $objReader->getAttribute('key');
						if ($params['assignee'] == 'specify') {
							$params['assigneeName'] = $objReader->readString();
						}
					
					}
					
					if($objReader->nodeType == 1 && $objReader->localName == 'issuestatus' && $objReader->hasAttributes) {
						$params['statuses'][] = $objReader->getAttribute('value');
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'resolution' && $objReader->hasAttributes) {
						$params['resolutions'][] = $objReader->getAttribute('value');
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'priority' && $objReader->hasAttributes) {
						$params['priorities'][] = $objReader->getAttribute('value');
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'created' && $objReader->hasAttributes) {
						if ($objReader->getAttribute('after')) {
							$params['createdAfter'] = $objReader->getAttribute('after');
						}
						if ($objReader->getAttribute('before')) {
							$params['createdBefore'] = $objReader->getAttribute('before');
						}
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'updated' && $objReader->hasAttributes) {
						if ($objReader->getAttribute('after')) {
							$params['updatedAfter'] = $objReader->getAttribute('after');
						}
						if ($objReader->getAttribute('before')) {
							$params['updatedBefore'] = $objReader->getAttribute('before');
						}
					}
					if($objReader->nodeType == 1 && $objReader->localName == 'duedate' && $objReader->hasAttributes) {
						if ($objReader->getAttribute('after')) {
							$params['duedateAfter'] = $objReader->getAttribute('after');
						}
						if ($objReader->getAttribute('before')) {
							$params['duedateBefore'] = $objReader->getAttribute('before');
						}
					}
			}
		return $params;
	}
	
	protected function _buildWhere($params)
	{
		$where = "1=1";
		$i = 0;
		for($i = 0 ; $i < count($params['projects']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "project = ". $params['projects'][$i];
			if($params['projects'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['issuetypes']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "issuetype = ". $params['issuetypes'][$i];
			if($params['issuetypes'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		if($params['reporter']) {
			if($params['reporter'] == 'any') {
			
			} elseif ($params['reporter'] == 'no') {
				$where .= " AND issue.reporter = ''";
			} elseif ($params['reporter'] == 'current') {
				$auth = Zend_Auth::getInstance();
				if($auth->getIdentity()) {
					$userInfo = $auth->getStorage()->read();
					$where .= " AND issue.reporter = '".$userInfo->fullname."'";
				}
			} elseif ($params['reporter'] == 'specify' && isset($params['reporterName'])) {
				$where .= " AND issue.reporter = '".$params['reporterName']."'";
			}
		}
		
		if($params['assignee']) {
			if($params['assignee'] == 'any') {
			
			} elseif ($params['assignee'] == 'no') {
				$where .= " AND issue.assignee = ''";
			} elseif ($params['assignee'] == 'current') {
				$auth = Zend_Auth::getInstance();
				if($auth->getIdentity()) {
					$userInfo = $auth->getStorage()->read();
					$where .= " AND issue.assignee = '".$userInfo->fullname."'";
				}
			} elseif ($params['assignee'] == 'specify' && isset($params['assigneeName'])) {
				$where .= " AND issue.assignee = '".$params['assigneeName']."'";
			}
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['fixVersions']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "issue.id IN (SELECT source_node_id FROM nodeassociation where association_type ='IssueFixVersion' AND sink_node_id = ". $params['fixVersions'][$i].")";
			if($params['fixVersions'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		
		$i = 0;
		for($i = 0 ; $i < count($params['components']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "issue.id IN (SELECT source_node_id FROM nodeassociation where association_type ='IssueComponent' AND sink_node_id = ". $params['components'][$i].")";
			if($params['components'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['affectVersions']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "issue.id IN (SELECT source_node_id FROM nodeassociation where association_type ='IssueVersion' AND sink_node_id = ". $params['affectVersions'][$i].")";
			if($params['affectVersions'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		
		//Zend_Debug::dump($params);
		if($params['query']['text'] != '') {
			$flag = false;
			$where .= " AND (";
			if($params['query']['summary']) {
				$where .= "summary like '%". $params['query']['text']."%'";
				$flag = true;
			}
			if($params['query']['description']) {
				if($flag) {
					$where .= " OR ";
				}
				$where .= "issue.description like '%". $params['query']['text']."%'";
				$flag = true;
			}
			if($params['query']['comments']) {
				if($flag) {
					$where .= " OR ";
				}
				$where .= "issue.id IN (SELECT issueid from action where action_type = 'comment' AND action_body like '%".$params['query']['text']."%')";
				$flag = true;
			}
			/*if($params['query']['description']) {
				if($flag) {
					$where .= " OR ";
				}
				$where .= "description =". $params['query']['description'];
				$flag = true;
			}*/
			if ($flag == false) {
				$where .= "summary like '%". $params['query']['text']."%'";
				$where .= " OR issue.description like '%". $params['query']['text']."%'";
				$where .= " OR issue.id IN (SELECT issueid from action where action_type = 'comment' AND action_body like '%".$params['query']['text']."%')";
				//$where .= "summary =". $params['query']['summary'];
				//$where .= "summary =". $params['query']['summary'];
			}
			$where .= ")";
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['statuses']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "issuestatus = ". $params['statuses'][$i];
			if($params['statuses'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['resolutions']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "resolution = ". $params['resolutions'][$i];
			if($params['resolutions'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		$i = 0;
		for($i = 0 ; $i < count($params['priorities']); $i++) {
			if ($i == 0) {
				$where .= " AND (";
			}
			$where .= "priority = ". $params['priorities'][$i];
			if($params['priorities'][$i+1]) {
				$where .= " OR ";
			} else {
				$where .= ')';
			}
		}
		
		if ($params['createdAfter']) {
			$where .= " AND created > '".date('Y-m-d',strtotime($params['createdAfter']))."'";
		}
		
		if ($params['createdBefore']) {
			$where .= " AND created < '".date('Y-m-d',strtotime($params['createdBefore']))."'";
		}
		
		if ($params['createdPrevious']) {
			//$where .= "";
		}
		if($params['createdNext']) {
		
		}
		
		if ($params['updatedAfter']) {
			$where .= " AND updated > '".date('Y-m-d',strtotime($params['updatedAfter']))."'";
		}
		
		if ($params['updatedBefore']) {
			$where .= " AND updated < '".date('Y-m-d',strtotime($params['updatedBefore']))."'";
		}
		
		if ($params['updatedPrevious']) {
			//$where .= "";
		}
		if($params['updatedNext']) {
		
		}
		
		if ($params['duedateAfter']) {
			$where .= " AND duedate > '".date('Y-m-d',strtotime($params['duedateAfter']))."'";
		}
		
		if ($params['duedateBefore']) {
			$where .= " AND duedate < '".date('Y-m-d',strtotime($params['duedateBefore']))."'";
		}
		
		if ($params['duedatePrevious']) {
			//$where .= "";
		}
		if($params['duedateNext']) {
		
		}
		//echo $where;exit;
		return $where;
	}
	
}